package com.yuandian.management.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 业务步骤批量导入工具类
 * <p>
 *
 * @author lijunhang
 * @date 2021/9/15
 * @since 1.0.0
 */

public class ExcelBatchUtil {

    //读取单个sheet，返回数据
    public static <T> void getSheet(MultipartFile multipartFile, int sheetNo, Class<T> rowModel, AnalysisEventListener listener) throws IOException {
        InputStream inputStream = getInputStream(multipartFile);
        ReadSheet readSheet = EasyExcel.readSheet(sheetNo)
                .head(rowModel)
                .registerReadListener(listener)
                .build();
        ExcelReader excelReader = EasyExcel.read(inputStream).build();
        try {
            excelReader.read(readSheet);
        } finally {
            if (excelReader != null) {
                // 这里要关闭，读的时候会创建临时文件，不关闭会导致磁盘崩溃
                excelReader.finish();
            }
        }
    }

    /**
     * 获取输入流
     *
     * @param excel 需要解析的Excel文件
     * @return ExcelReader
     * @throws IOException
     */
    private static InputStream getInputStream(MultipartFile excel) throws IOException {
        if (excel == null) {
            throw new IOException("文件错误！");
        }
        String fileName = excel.getOriginalFilename();
        if (fileName == null) {
            throw new IOException("文件格式错误！");
        }
        if (!fileName.toLowerCase().endsWith(ExcelTypeEnum.XLS.getValue()) && !fileName.toLowerCase().endsWith(ExcelTypeEnum.XLSX.getValue())) {
            throw new IOException("文件格式错误！");
        }
        return excel.getInputStream();
    }

    /**
     * 写到不同的sheet 不同的对象
     * 注意每个集合的最大数据量
     *
     * @param rowModels  要导出的对象数组
     * @param filePath   文件路径
     * @param sheetNames sheet名称数组
     * @param dataList   导出数据数组
     */
    public static void writeExcel(Class[] rowModels, HttpServletResponse response, String excelName, String[] sheetNames, List[] dataList) throws IOException {

        response.reset();
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode(excelName, "utf-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try {
            // 指定文件
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            // 调用写入
            for (int i = 0; i < rowModels.length; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i, sheetNames[i]).head(rowModels[i]).build();
                excelWriter.write(dataList[i], writeSheet);
            }
        } finally {
            // 关闭流
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }





}
